package com.dykj.fireFighting.web.base.analysis.controller;


import com.dykj.fireFighting.api.base.analysis.dto.MaintenanceDto;
import com.dykj.fireFighting.api.base.maintenance.dto.UrgentMaintenanceDto;
import com.dykj.fireFighting.api.base.maintenance.service.IUrgentMaintenanceService;
import com.dykj.fireFighting.api.base.maintenance.vo.MaintenanceEvaluationVo;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务机构
 */
@Slf4j
@Api(value = "服务机构", tags = {"服务机构接口"})
@RestController
@RequestMapping("/maintenance")
public class OrganizationController {


    @DubboReference
    private IUrgentMaintenanceService urgentMaintenanceService;


    /**
     * 维保机构当月所有被服务的社会单位评价得分的平均值
     *
     * @param urgentMaintenanceDto
     * @return
     */
    @GetMapping("/list")
    public CommonResult<PageVo<MaintenanceEvaluationVo>> getData(UrgentMaintenanceDto urgentMaintenanceDto) {
        //获取用户类型，监控中心查下辖的单位，社会单位查自己，管理员查全部社会单位
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        String jkzxUnitId = loginUserVo.getEnterpriseId().toString();
        String maintenanceDept = urgentMaintenanceDto.getMaintenanceDept();
        String date = urgentMaintenanceDto.getEvaluationTime();
        if (StringUtils.isNotBlank(date)) {
            date = date.substring(0, 7) + "-01";
        }
        List<MaintenanceEvaluationVo> returnSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, maintenanceDept, date);

        //split page
        long page = urgentMaintenanceDto.getPage();
        long limit = urgentMaintenanceDto.getLimit();
        List<MaintenanceEvaluationVo> subList = returnSocreList.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        PageVo<MaintenanceEvaluationVo> pageVo = new PageVo<>();
        pageVo.setList(subList);
        pageVo.setTotalCount(returnSocreList.size());
        return CommonResult.success(pageVo);
    }


    /**
     * echarts数据
     *
     * @param maintenanceDto
     * @return
     * @throws Exception
     */
    @GetMapping("/rankingEcharts")
    public CommonResult<PageVo<MaintenanceEvaluationVo>> getRankingEchartsData(MaintenanceDto maintenanceDto) throws Exception {
        List<MaintenanceEvaluationVo> allList = new ArrayList<>();

        //获取用户类型，监控中心查下辖的单位，社会单位查自己，管理员查全部社会单位
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        String jkzxUnitId = loginUserVo.getEnterpriseId().toString();

        if (maintenanceDto.getType() == 2) {
            if (StringUtils.isNotBlank(maintenanceDto.getEvaluationTime())) {
                int year = Integer.parseInt(maintenanceDto.getEvaluationTime().substring(0, 4));
                int month = Integer.parseInt(maintenanceDto.getEvaluationTime().substring(5, 7));
                for (int i = 0; i < 3; i++) {
                    int num = month + i;
                    String date = year + "-" + UUIDUtils.int2str(num) + "-01";
                    List<MaintenanceEvaluationVo> returnSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, null, date);
                    allList.addAll(returnSocreList);
                }
            }
        } else if (maintenanceDto.getType() == 1) {
            if (StringUtils.isNotBlank(maintenanceDto.getEvaluationTime())) {
                String year = maintenanceDto.getEvaluationTime().substring(0, 4);
                for (int i = 1; i < 13; i++) {
                    String date = year + "-" + UUIDUtils.int2str(i) + "-01";
                    List<MaintenanceEvaluationVo> returnSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, null, date);
                    allList.addAll(returnSocreList);
                }
            }
        } else {
            String date = maintenanceDto.getEvaluationTime() + "-01";
            List<MaintenanceEvaluationVo> returnSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, null, date);
            allList.addAll(returnSocreList);
        }

        //list排序
        //根据某个属性分组，汇总某个属性
        Map<String, BigDecimal> collect2 = allList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getMaintenanceName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));

        List<MaintenanceEvaluationVo> resultList = new ArrayList<>();
        collect2.forEach((key, value) -> {
            MaintenanceEvaluationVo result = new MaintenanceEvaluationVo();
            result.setMaintenanceName(key);
            result.setMonthAvgScore(value.setScale(2, BigDecimal.ROUND_HALF_UP));
            resultList.add(result);
        });

        //list排序
        Integer[] arr = {1};
        List<MaintenanceEvaluationVo> returnSocreList = resultList.stream().sorted(Comparator.comparing(MaintenanceEvaluationVo::getMonthAvgScore).reversed())
                .peek(e -> e.setRanking(arr[0]++)).collect(Collectors.toList());

        //split page
        long page = maintenanceDto.getPage();
        long limit = maintenanceDto.getLimit();
        List<MaintenanceEvaluationVo> subList = returnSocreList.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        PageVo<MaintenanceEvaluationVo> pageVo = new PageVo<>();
        pageVo.setList(subList);
        pageVo.setTotalCount(returnSocreList.size());
        return CommonResult.success(pageVo);
    }


}
